#include "../include/head.h"
// 链表相关
// 创建链表函数
LinkList createList()
{
    LinkList head = (LinkList)malloc(sizeof(LNode));
    head->next = NULL;
    head->prior = NULL;
    return head;
}
// 头插
int list_head_insert(LinkList H, goodsNode value)
{
    LinkList newNode = (LinkList)malloc(sizeof(LNode));
    LinkList head = H;
    if (head == NULL)
    {
        printf("空间有问题\n");
    }

    if (newNode == NULL)
    {
        printf("内存分配失败\n");
        return -1;
    }
    // // 设置新节点数据
    newNode->data = value;
    newNode->prior = NULL;
    newNode->next = NULL;
    // // 设置新节点的next指向头结点的下一个结点
    newNode->next = head->next;
    if (head->next != NULL)
    {
        head->next->prior = newNode;
    }
    // // 新节点的前驱指向头结点
    newNode->prior = head;
    // // 头结点的后驱指向新节点
    head->next = newNode;

    return 0;
}
// 尾插
int list_tail_insert(LinkList H, goodsNode value)
{
    LinkList head = H;
    LinkList node = (LinkList)malloc(sizeof(LNode));
    if (node == NULL)
    {
        printf("内存分配失败\n");
        return -1;
    }
    node->data = value;
    node->next = NULL;

    while (head->next)
    {
        head = head->next;
    }
    node->prior = head;
    head->next = node;
}
// 根据名称查找
LinkList list_find_by_name(LinkList L, char *name)
{
    LinkList head = L;
    while (head->next)
    {
        if (strcmp(head->next->data.name, name) == 0)
        {
            return head->next;
        }
        head = head->next;
    }
    return head;
}
// 减少商品数量
int list_reduce_num(LinkList L, char *name, int num)
{
    LinkList head = L;
    while (head->next)
    {
        if (strcmp(head->next->data.name, name) == 0)
        {
            head->next->data.num -= num;
            return 0;
        }
        head = head->next;
    }
    return -1;
}

#define BORDER_WIDTH 97
void list_printf(LinkList L)
{
    // 打印上边框
    for (size_t i = 0; i < BORDER_WIDTH; i++)
    {
        printf("=");
    }
    printf("\n");

    // 打印表头
    char header[BORDER_WIDTH + 1];
    printf("名称\t\t价格\t\t货架位置\t\t数量\n"); // 简化版，可能需要根据实际终端调整制表符宽度

    for (size_t i = 0; i < BORDER_WIDTH; i++)
    {
        printf("-");
    }
    printf("\n");

    // 打印数据行
    LinkList p = L->next; // 假设L是指向头节点的指针，且头节点不存储数据
    while (p)
    {
        printf("%-10s\t%.2f\t%-15s\t%d\n", p->data.name, p->data.price, p->data.location, p->data.num);
        p = p->next;
    }

    // 打印下边框
    for (size_t i = 0; i < BORDER_WIDTH; i++)
    {
        printf("=");
    }
    printf("\n");
}